#pragma once

#include<iostream>
#include<string>
#include<set>
#include<fstream>

#include"Log.hpp"

class Command
{
public:
    Command(std::string save_command_path="save_command.txt")
    {
        std::ifstream in(save_command_path);
        if(!in.is_open())
        {
            Log(FATAL,"can not open file %s",save_command_path);
            return;
        }
        std::string line;
        while(std::getline(in,line))
        {
            _s.insert(line);
        }
        in.close();
    }

    bool IsSaveCommand(std::string& command)
    {
        if(_s.end()!=_s.find(command))
        {
            return true;
        }

        return false;
    }

    std::string Execute(std::string command)
    {
        std::string result;
        if(IsSaveCommand(command))
        {
            FILE* fp=popen(command.c_str(),"r");
            if(nullptr==fp)
            {
                return "execute error\n";
            }
            char buf[1024];
            while(fgets(buf,sizeof(buf),fp))
            {
                result+=buf;
            }
        }
        else
        {
            return "illegal command\n";
        }

        return result;
    }
private:
    std::set<std::string> _s;
};